package com.wish.blessingroad.util;

import org.apache.ibatis.session.RowBounds;

/**
 * 分页组件，页码从0开始
 * 
 * @author dhc
 *
 */
public class Pager {

    private int pageSize;
    private int total;
    private int page;

    public Pager(int pageSize) {
        this(pageSize, 0);
    }

    public Pager(int pageSize, int page) {
        this.pageSize = pageSize;
        this.page = Math.max(page, 0);
    }

    public int getTotal() {
        return total;
    }

    public void setTotal(int total) {
        this.total = total;
    }

    public int getPageSize() {
        return pageSize;
    }

    public void setPageSize(int pageSize) {
        this.pageSize = pageSize;
    }

    public int getPage() {
        return page;
    }

    public void setPage(int page) {
        this.page = page;
    }

    /**
     * 不关心总记录数
     *
     * @param pageNumber
     * @param pageSize
     * @return
     */
    public static int getPageStart(int pageNumber, int pageSize) {
        return (pageNumber - 1) * pageSize;
    }

    /**
     * 计算分页获取数据时游标的起始位置
     *
     * @param totalCount 所有记录总和
     * @param pageNumber 页码,从1开始
     * @return
     */
    public static int getPageStart(int totalCount, int pageNumber, int pageSize) {
        int start = (pageNumber - 1) * pageSize;
        if (start >= totalCount) {
            start = 0;
        }

        return start;
    }


    /**
     * 获取总页数
     * 
     * @return
     */
    public int getTotalPages() {
        return (this.total + this.pageSize - 1) / this.pageSize;
    }

    /**
     * 获取当前页的元素个数
     * 
     * @return
     */
    public int getCurrentPageCount() {
        return Math.max(Math.min(total - getOffset(), pageSize), 0);
    }

    /**
     * 获取当前页面的首个元素在所有元素中的偏移量
     * 
     * @return
     */
    public int getOffset() {
        return page * pageSize;
    }

    public RowBounds asRowBounds() {
        return new RowBounds(this.getOffset(), this.pageSize);
    }

    public static void main(String[] args) {
        var pager = new Pager(10, 2);
        pager.setTotal(100);

        System.out.println(pager.getPage());
    }

}
